package buaa.paas.kubectl;

import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Service
public class ServiceUtil {
    @Autowired
    ApiUtil apiUtil;
    /**
     * 对一个service的简介
     * @param s 被简介的service
     * @return 这个service的简介的信息，包括这个服务的名字、类型、NodePort、TargetPort、selector
     * */
    public static Map<String, Object> briefService(V1Service s){
        TreeMap<String, Object> result = new TreeMap<>();
        result.put("Type", s.getSpec().getType());
        result.put("Name", s.getMetadata().getName());
        result.put("Selectors", s.getSpec().getSelector());
        TreeMap<Integer, Integer> transfers = new TreeMap<>();
        for(V1ServicePort p: s.getSpec().getPorts()){
            transfers.put(p.getNodePort(), p.getPort());
        }
        result.put("ports", transfers);
        return result;
    }

    /**
     * 展示一个namespace下的全部service
     * */
    public List<Map<String,Object>> listServices(String namespace) throws ApiException {
        V1ServiceList sList = apiUtil.getCoreApi().listNamespacedService(namespace, null, null, null, null, null, null,null, null, null);
        List<Map<String, Object>> result = new LinkedList<>();
        for(V1Service s:sList.getItems()){
            result.add(briefService(s));
        }
        return result;
    }

    /**
     * 删除一个namespace下面的service
     * */
    public void deleteService(String namespace, String name) throws ApiException {
        apiUtil.getCoreApi().deleteNamespacedService(name, namespace, null, null, null, null, null, null);
    }

    /**
     * 创建一个service
     * @param name 这项服务的名字
     * @param namespace 这项服务所在的namespace
     * @param selector 被这项服务选中的deployment
     * @param labels 这项服务的相关的labels
     * @param transfer 交换的对象
     * */
    public void createService(String name, String namespace, Map<String, String>labels, Map<String, String> selector, Map<Integer, Integer> transfer) throws ApiException {
        List<V1ServicePort> list = new LinkedList<>();
        for(int i: transfer.keySet()){
            list.add(new V1ServicePortBuilder().withNodePort(i).withPort(transfer.get(i)).build());
        }
        V1ServiceBuilder builder = new V1ServiceBuilder();
        builder.withKind("Service").withApiVersion("v1").withNewMetadata().withName(name).withNamespace(namespace).withLabels(labels).endMetadata();
        builder.withNewSpec().withType("NodePort").withSelector(selector).withPorts(list).endSpec();
        V1Service service = builder.build();
        apiUtil.getCoreApi().createNamespacedService(namespace, service, null, null, null);
    }
}
